package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    @CacheEvict(value = "categoryCache", allEntries = true)
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    @GetMapping("/page")
    @Cacheable(value = "categoryCache", key = "#page+'_'+#pageSize+'_'+#name")
    public R<Page> page(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);
        log.info("name={}", name);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>();
        if (name != null) queryWrapper.like(Category::getName, name);
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, queryWrapper);
        log.info("查询结果：size={},total={}", pageInfo.getSize(), pageInfo.getTotal());
        return R.success(pageInfo);

    }

    @DeleteMapping
    @CacheEvict(value = "categoryCache", allEntries = true)
    public R<String> delete(Long ids) {
        categoryService.remove(ids);
        return R.success("分类信息删除成功");
    }

    @PutMapping
    @CacheEvict(value = "categoryCache", allEntries = true)
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "categoryCache", key = "#category.type==null?'_':#category.type")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryService.list(queryWrapper);

        return R.success(categories);
    }
}
